<template>
  <div class="account-main">
    <!-- 账号管理 -->
    <el-card shadow="never" class="margin-30" :body-style="{ padding: '20px' }">
      <!--  -->
      <el-form ref="userMsgForm" :model="userMsg" label-width="80px" :inline="false" size="mini">
        <el-row :gutter="20">
          <el-col :span="6" :offset="0">
            <el-form-item label="昵称">
              <el-input v-model="userMsg.nickName" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="用户名">
              <el-input v-model="userMsg.username" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="4" :offset="16">
            <el-form-item>
              <el-button>重置</el-button>
              <el-button type="primary">查询</el-button>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

    </el-card>

    <!-- 列表 -->
    <el-card shadow="never" class="margin-30" :body-style="{ padding: '20px' }">
      <div slot="header">
        <el-button type="primary" size="mini" @click="addUserOrRoles">新增</el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="userList"
        border
        stripe
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        style="width: 100%"
      >
        >
        <el-table-column type="index" label="#" width="50" align="center" />
        <el-table-column prop="username" label="用户名" width="150" align="center" />
        <el-table-column prop="nick_name" label="昵称" width="180" align="center" />
        <el-table-column label="头像" width="130" align="center">
          <template slot-scope="scope">
            <el-image style="width: 80px; height: 80px;" :src="scope.row.salt" fit="fill" />
          </template>
        </el-table-column>
        <el-table-column prop="roles" label="角色" align="center" />
        <el-table-column prop="create_time" label="添加时间" width="180" align="center" />
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button type="success" size="mini" @click="doEditUserItem(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="mini" @click="doDelUser(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 新增框 -->
      <el-dialog title="编辑用户" :visible.sync="dialogVisible" width="30%">
        <el-form
          ref="AddUserForm"
          :model="AddOrEditUserList"
          :rules="rules"
          label-width="80px"
          :inline="false"
          size="mini"
        >
          <el-row :gutter="20">
            <el-col :span="20" :offset="0">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="AddOrEditUserList.username" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="20" :offset="0">
              <el-form-item label="用户昵称" prop="nickName">
                <el-input v-model="AddOrEditUserList.nickName" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="20" :offset="0">
              <el-form-item label="密码" prop="password">
                <el-input v-model="AddOrEditUserList.password" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="20" :offset="0">
              <el-form-item label="用户头像" prop="salt">
                <el-upload
                  class="avatar-uploader"
                  :action="uploadFileOss"
                  :headers="token"
                  :show-file-list="false"
                  :on-success="handleAddUserImgSucc"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="AddOrEditUserList.salt" :src="AddOrEditUserList.salt" class="avatar">
                  <i v-else class="el-icon-user-solid avatar-uploader-icon" />
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="20" :offset="0">
              <el-form-item label="选择角色" prop="roleIds">
                <el-select v-model="AddOrEditUserList.roleIds" multiple placeholder="请选择">
                  <el-option v-for="item in AllRoles" :key="item.id" :label="item.roleName" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="getCancel">取 消</el-button>
          <el-button type="primary" @click="doSaveUserRoles">{{ isEdit ? '确定修改' : '点击新增' }}</el-button>
        </span>
      </el-dialog>

      <!-- 分页 -->
      <div class="block">
        <el-pagination
          style="margin-top: 10px; text-align: center;"
          :current-page="start"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="limit"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

  </div>
</template>

<script>
import mix from '@/mixins'
import { findUsersByPage, removeUser, saveUserRoles, getuserDetails, updateUserRoles } from '@/api/userController/user'
import { findAllRoles } from '@/api/userController/role'

export default {
  name: 'Account',
  mixins: [mix],
  data() {
    return {
      userMsg: {},
      userList: [],
      dialogVisible: false,
      AddOrEditUserList: {},
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        salt: [
          { required: true, message: '用户头像必选', trigger: 'blur' }
        ],
        roleIds: [
          { required: true, message: '角色必选', trigger: 'blur' }
        ]
      },
      AllRoles: [],
      loading: true,
      isEdit: false
    }
  },
  created() {
    this.getUserByPage()
    this.getAllfindAllRoles()
  },

  mounted() {

  },

  methods: {
    // 编辑
    async doEditUserItem(id) {
      // 打开卡片,获取用户明细,将值传递给
      this.dialogVisible = true
      // 设置一个值确定是新增还是编辑
      this.isEdit = true
      const res = await getuserDetails(id)
      const { data: { user }, success } = res
      if (success) {
        this.AddOrEditUserList = user
      }
    },

    // 点击新增 / 编辑
    doSaveUserRoles() {
      this.$refs.AddUserForm.validate(async(valid) => {
        if (valid) {
          // 校验通过
          if (this.isEdit) {
            const res = await updateUserRoles(this.AddOrEditUserList)
            const { success } = res
            if (success) {
              this.$message.success('修改成功')
              this.dialogVisible = false
              this.AddOrEditUserList = {}
            }
          } else {
            const res = await saveUserRoles(this.AddOrEditUserList)
            const { success } = res
            if (success) {
              this.$message.success('添加成功')
              this.dialogVisible = false
              this.AddOrEditUserList = {}
            }
          }
        } else {
          return false
        }
      })
    },
    // 取消新增
    getCancel() {
      // 清空内容
      this.dialogVisible = false
      this.AddOrEditUserList = {}
    },

    // 打开新增卡片
    addUserOrRoles() {
      this.dialogVisible = true
    },

    // 获取所有角色
    async getAllfindAllRoles() {
      const res = await findAllRoles()
      console.log(res)
      const { data: { items }, success } = res
      if (success) {
        this.AllRoles = items
      }
    },

    // 新增图片
    handleAddUserImgSucc(res) {
      console.log(res)
      const { data: { fileUrl }} = res
      this.$set(this.AddOrEditUserList, 'salt', fileUrl)
    },

    // 删除
    doDelUser(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await removeUser(id)
        const { success } = res
        if (success) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getUserByPage()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 获取列表
    async getUserByPage() {
      const res = await findUsersByPage(this.start, this.limit)
      console.log(res)
      const { data: { rows, total }, success } = res
      if (success) {
        this.userList = rows
        this.total = total
        this.loading = false
      } else {
        this.$message.waring('获取失败,请刷新后重试')
      }
    },
    // 分页
    handleSizeChange(val) {
      this.loading = true
      this.limit = val
      this.start = 1
      this.getUserByPage()
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.loading = true
      this.start = val
      this.getUserByPage()
      // console.log(`当前页: ${val}`);
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 18px;
  color: #ffffff;
  width: 35px;
  height: 35px;
  line-height: 35px;
  text-align: center;
  background-color: #d4d4d4;
  border-radius: 50%;
}

.avatar {
  width: 35px;
  height: 35px;
  border-radius: 50%;
  display: block;
}

// ::v-deep .el-form-item__content{
//   margin-left: 0 !important;
// }

// ::v-deep  .el-form-item{
//   display: flex;
//   align-items: center;
// }
</style>
